package com.http.nio.core;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author YL
 */
public class StaticViewServlet implements CloudServlet {


    private String staticRootPath;
    private static Pattern p = Pattern.compile("^/static/\\S+");

    @Override
    public boolean match(Request request) {
        String path = request.getPath();
        Matcher matcher = p.matcher(path);
        return matcher.matches();
    }

    @Override
    public void init(Request request, Response response) {
        // TODO: 2019/11/12 指定静态资源地址
        staticRootPath = "C:/Users/YL/Downloads/nginx-1.14.0/nginx-1.14.0/html/";
    }

    @Override
    public void doService(Request request, Response response) {
        String path = request.getPath();
        String absolutePath = staticRootPath + path;
        File file = new File(absolutePath);

        if (!file.exists()) {
            // 设置错误码
            response.setCode(404);
            try {
                response.getOutPutStream().write(("页面丢了啊：" + absolutePath).getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(file, "r");
            FileChannel fileChannel = randomAccessFile.getChannel();
            ByteBuffer htmBuffer = ByteBuffer.allocate((int) fileChannel.size());
            fileChannel.read(htmBuffer);
            htmBuffer.flip();
            byte[] htmByte = new byte[htmBuffer.limit()];
            htmBuffer.get(htmByte);
            response.getOutPutStream().write(htmByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
